package com.kis.ioc.util;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by yks on 15-11-14.
 */
public class ScanUtil {
    /**
     *
     * @param packageName 给定包名
     * @return
     */
    public static Class[] getClasses(String packageName){
        Class cls = ScanUtil.class;
        String path = packageName.replace(".","/");
        ArrayList<Class> classes = new ArrayList<Class>();
        try {
            System.out.println(cls.getClassLoader().getResource(path));
            Enumeration<URL> resource = cls.getClassLoader().getResources(path);
            List<File> files = new ArrayList<File>();
            while (resource.hasMoreElements()){
                URL url = resource.nextElement();
                files.add(new File(url.getFile()));
            }
            for (File file : files) {
                classes.addAll(findClasses(file,packageName));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return classes.toArray(new Class[classes.size()]);
    }

    private static List<Class> findClasses(File directory, String packageName)
            throws ClassNotFoundException {
        List<Class> classes = new ArrayList<Class>();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                classes.addAll(findClasses(file,
                        packageName + "." + file.getName()));
            } else if (file.getName().endsWith(".class")) {
                classes.add(Class.forName(packageName
                        + '.'
                        + file.getName().substring(0,
                        file.getName().length() - 6)));
            }
        }
        return classes;
    }

}
